package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import com.sky.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Api(tags = "菜品管理")
@RequestMapping("/admin/dish")
@RestController
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dto
     * @return
     */
    @ApiOperation("新增菜品")
    @PostMapping
    public Result add(@RequestBody DishDTO dto) {
        // 添加菜品数据到数据库
        dishService.add(dto);
        // 清除缓存
        redisTemplate.delete("dish_" + dto.getCategoryId());
        return Result.success();
    }

    /**
     * 分页查询菜品
     *
     * @return
     */
    @ApiOperation("分页查询菜品")
    @GetMapping("/page")
    public Result page(DishPageQueryDTO dto) {
        return Result.success(dishService.page(dto));
    }

    /**
     * 删除菜品
     *
     * @param ids
     * @return
     */
    @ApiOperation("删除菜品")
    @DeleteMapping
    public Result delete(@RequestParam List<Long> ids) {
        dishService.delete(ids);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return Result.success();
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @ApiOperation("根据id查询菜品")
    @GetMapping("/{id}")
    public Result findById(@PathVariable Long id) {
        return Result.success(dishService.findById(id));
    }

    /**
     * 修改菜品
     * @param dto
     * @return
     */
    @ApiOperation("修改菜品")
    @PutMapping
    public Result update(@RequestBody DishDTO dto){
        dishService.update(dto);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return Result.success();
    }

    /**
     * 菜品停售启售
     * @param status
     * @param id
     * @return
     */
    @ApiOperation("菜品停售启售")
    @PostMapping("/status/{status}")
    public Result updateStart(@PathVariable Integer status, Long id){
        dishService.updateStart(status,id);
        return Result.success();
    }

    /**
     * 根据类型查询分类
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据类型查询分类")
    public Result list(Long categoryId) {
        return Result.success( dishService.list(categoryId));
    }
}
